<template>
    <div class="goods-add">
            <el-form :inline="true" :model="eleForm" :rules="rules" label-width="65px" size="medium" ref="eleForm" @keyup.enter.native="onSubmit">
                <el-row>
                    <el-form-item label="名称" prop="goodsname">
                        <el-input v-model.trim="eleForm.goodsname" style="width:200px" placeholder="请输入商品名称"></el-input>
                    </el-form-item>
                    <el-form-item label="价格" prop="price">
                        <el-input v-model.trim="eleForm.price" type="number" style="width:200px" placeholder="请输入商品价格"></el-input>
                    </el-form-item>
                    <el-form-item label="发货地" prop="goodsAddress">
                        <el-input v-model.trim="eleForm.goodsAddress" style="width:200px" placeholder="请输入发货地址"></el-input>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="描述" prop="describe">
                        <el-input type="textarea" v-model.trim="eleForm.describe" style="width:475px" placeholder="请输入商品描述"></el-input>
                    </el-form-item>
                    <el-form-item label="分类" prop="goodsType">
                        <el-select v-model="eleForm.goodsType" placeholder="请选择类别" style="width:200px" filterable clearable>
                            <el-option :label="item.value" :value="item.value" v-for="item in opt_goodsType" :key="item.goodsAddress"></el-option>
                        </el-select>
                        <!-- <el-input v-model.trim="eleForm.goodsType" style="width:200px" placeholder="请输入发货地址"></el-input> -->
                    </el-form-item>
                </el-row>
                <el-row>
                    <div class="img-upolad">
                        <div class="quan-label">
                            <span style="padding-left:28px">照片</span>
                        </div>
                        <div class="quan-img">
                            <div class="img-oper" v-if="eleForm.goodsImg">
                                <img :src="eleForm.goodsImg" alt="">
                                <div class="oper">
                                    <span class="el-icon-zoom-in" @click="showBigImage(eleForm.goodsImg)"></span>
                                    <span style="margin-left:10px" class="el-icon-delete" @click="deleteImage(3,eleForm.goodsImg)"></span>
                                </div>
                            </div>
                            <el-upload v-else class="goods-img-upload" :action="imgUrl" :headers="getHeaders()" :show-file-list="false" :before-upload="handleBeforeUpload" :on-success="handleSuccess1" name="goodsImg">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                        </div>
                    </div>
                </el-row>
                <el-row style="margin-top:15px">
                    <div class="img-upolad">
                        <div class="quan-label">
                            <span>细节照片</span>
                        </div>
                        <div class="quan-img">
                            <div class="img-oper" v-for="(item,index) in eleForm.goodsShowImg" :key="index">
                                <img :src="item" alt="">
                                <div class="oper">
                                    <span class="el-icon-zoom-in" @click="showBigImage(item)"></span>
                                    <span style="margin-left:10px" class="el-icon-delete" @click="deleteImage(1,item)"></span>
                                </div>
                            </div>
                            <el-upload class="goods-img-upload" :action="imgUrl" :headers="getHeaders()" multiple :limit='6' :on-exceed="exceed" :show-file-list="false" :before-upload="handleBeforeUpload" :on-success="handleSuccess2" name="goodsImg">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                        </div>
                    </div>
                </el-row>
                <el-row style="margin-top:15px">
                    <div class="img-upolad">
                        <div class="quan-label">
                            <span>详情照片</span>
                        </div>
                        <div class="quan-img">
                            <div class="img-oper" v-for="(item,index) in eleForm.goodsDetailsImg" :key="index">
                                <img :src="item" alt="">
                                <div class="oper">
                                    <span class="el-icon-zoom-in" @click="showBigImage(item)"></span>
                                    <span style="margin-left:10px" class="el-icon-delete" @click="deleteImage(2,item)"></span>
                                </div>
                            </div>
                            <el-upload class="goods-img-upload" :action="imgUrl" :headers="getHeaders()" multiple :limit='6' :on-exceed="exceed" :show-file-list="false" :before-upload="handleBeforeUpload" :on-success="handleSuccess3" name="goodsImg">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                        </div>
                    </div>
                </el-row>
            </el-form>
        <div style="text-align:center;margin-top:20px">
            <el-button @click="escClick">取消</el-button>
            <el-button type="primary" @click="onSubmit" :loading="submitLoading">提交</el-button>
        </div>
    </div>
</template>
<script>
// 发请求全部导入
import api from '@/api/goods/index'
// 工具
import tool from '@/utils/tool'
export default {
    props:['dialogInfo'],
    data() {
        return {
            // 提交时避免重复点击
            submitLoading:false,
            // 分类
            opt_goodsType:tool.goodsType,
            // 上传照片地址
            imgUrl:this.$url.goodsImageUpload,
            // 图片放大
            // 接受的数组
            viewUrl:[],

            eleForm:{
                goodsname:'',
                price:'',
                goodsAddress:'',
                describe:'',
                goodsType:'',
                goodsImg:'',
                goodsShowImg:[],
                goodsDetailsImg:[],
            },
            rules:{
                goodsname:[
                    {required:true,message:'请输入商品名称',trigger:'blur'},
                    {min:4,max:30,message:'长度在4到30个字符之间',trigger:'blur'}
                ],
                price:[
                    {required:true,message:'请输入价格',trigger:'blur'},
                ],
                goodsAddress:[
                    {required:true,message:'请输入商品发货地',trigger:'blur'},
                    {min:3,max:30,message:'长度在3到30个字符之间',trigger:'blur'}
                ],
                goodsType:[
                    {required:true,message:'请选择分类',trigger:'change'},
                ],
                describe:[
                    {min:4,max:100,message:'长度在4到100个字符之间',trigger:'blur'}
                ],
            },
        }
    },
    methods: {
        // 取消
        escClick(){
            this.$emit('dialogCancel')
        },
        // 提交
        onSubmit(){
            // 更新
            if(this.dialogInfo){
                this.$refs.eleForm.validate(valid=>{
                    if(!valid) return
                    // console.log(this.eleForm)
                    this.submitLoading = true
                    api.updateGoods(this.eleForm).then(res=>{
                        this.submitLoading = false
                        if(res.code !==200 ) return
                        console.log(res)
                        this.$message.success('更新成功!')
                        this.$emit('dialogSubmit')
                    })
                })
            // 新增
            }else{
                this.$refs.eleForm.validate(valid=>{
                    if(!valid) return
                    console.log(this.eleForm)
                    this.submitLoading = true
                    api.addGoods(this.eleForm).then(res=>{
                        this.submitLoading = false
                        if(res.code !==200 ) return
                        console.log(res)
                        this.$message.success('添加成功!')
                        this.$emit('dialogSubmit')
                    })
                })
            }
        },
        // 加token
        getHeaders(){
            var headers = {}
            headers["tokenKey"] = window.localStorage.getItem("tokenKey")
            return headers;
        },
        // 上传之前
        handleBeforeUpload(file){
            let isRightType = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/tiff' || file.type === 'image/bmp'||file.type === 'image/jpg';
            let is5M = file.size / 1024 / 1024 < 5;
            if (!isRightType) {
                this.$message.warning('上传图片只能是 JPG JPEG TIFF BMP PNG 格式!');
                return false
            }
            if (!is5M) {
                this.$message.warning('上传图片大小不能超过 5MB!');
                return false
            }
            return isRightType && is5M;
        },
        // 上传数量超出
        exceed(){
            this.$message.warning('当前限制选择6个文件，请重新选择！')
        },
        // （照片）上传成功(这些参数fileList包含file包含res)
        handleSuccess1(res,file,fileList){
            // 文件上传没有使用axios，这里的自己处理
            // 失效的时候，先清除，再去登录页
            if(res.code === 598){
                this.$message.warning(res.msg)
                localStorage.removeItem('tokenKey')
                localStorage.removeItem('by_menu')
                location.href = '/login'
            }

            if(res.code!==200) return
            this.eleForm.goodsImg = res.data[0].filename
        },
        // （细节照片）上传成功
        handleSuccess2(res,file,fileList){
            // 文件上传没有使用axios，这里的自己处理
            // 失效的时候，先清除，再去登录页
            if(res.code === 598){
                this.$message.warning(res.msg)
                localStorage.removeItem('tokenKey')
                localStorage.removeItem('by_menu')
                location.href = '/login'
            }

            if(res.code!==200) return
            // 这里自动上传，每上传一张就会有一个返回
            this.eleForm.goodsShowImg.push(res.data[0].filename)
            // console.log(this.eleForm.goodsShowImg)
        },
        // （详情照片）上传成功
        handleSuccess3(res,file,fileList){
            // 文件上传没有使用axios，这里的自己处理
            // 失效的时候，先清除，再去登录页
            if(res.code === 598){
                this.$message.warning(res.msg)
                localStorage.removeItem('tokenKey')
                localStorage.removeItem('by_menu')
                location.href = '/login'
            }

            if(res.code!==200) return
            this.eleForm.goodsDetailsImg.push(res.data[0].filename)
        },
        // 删除选中的图片
        deleteImage(flag,val){
            // 1是删除细节照片，2是删除详情照片，3是删除照片
            if(flag === 1){
                for(let i=0;i<this.eleForm.goodsShowImg.length;i++){
                    if(this.eleForm.goodsShowImg[i] === val) {
                        this.eleForm.goodsShowImg.splice(i,1)
                    }
                }
            }
            if(flag === 2){
                for(let i=0;i<this.eleForm.goodsDetailsImg.length;i++){
                    if(this.eleForm.goodsDetailsImg[i] === val) {
                        this.eleForm.goodsDetailsImg.splice(i,1)
                    }
                }
            }
            if(flag === 3){
                this.eleForm.goodsImg = ''
            }
        },
        // 放大图片
        showBigImage(url){
            this.viewUrl = []
            this.viewUrl.push(url)
            window.createPreview(this.viewUrl)
        }
    },
    created() {
        console.log(this.dialogInfo)
        if(this.dialogInfo){
            // 如果有,那就是更新操作(执行深拷贝，不然会影响父组件的数据------对象的传递传递的是引用)
            this.eleForm = JSON.parse(JSON.stringify(this.dialogInfo))
        }
    },
    mounted() {
    },
}
</script>
<style lang="less" scoped>
.goods-add{
    position: relative;
    margin-left: 7px;
    .img-upolad{
        position: relative;
        height: 80px;
        overflow: hidden;
        .quan-label{
            display: inline-block;
            width: 65px;
            height: 80px;
            text-align: center;
            vertical-align: top;
            span{
                padding-top: 30px;
                display: inline-block;
                width: 100%;
                text-align: left;
            }
        }
        .quan-img{
            display: inline-block;
            height: 80px;
            line-height: 80px;
            width: 770px;
            overflow: hidden;
            .goods-img-upload{
                display: inline-block;
                vertical-align: top;
                i{
                    font-size: 18px;
                    box-sizing: border-box;
                    border: 1px dashed #d9d9d9;
                    border-radius: 6px;
                    color: #8c939d;
                    width: 78px;
                    height: 78px;
                    line-height: 78px;
                    text-align: center;
                }
            }
            .img-oper{
                position: relative;
                display: inline-block;
                width: 78px;
                height: 78px;
                line-height: 78px;
                margin-right: 10px;
                img{
                    width: 78px;
                    height: 78px;
                    border-radius: 6px;
                    display: block;
                }
                .oper{
                    position: absolute;
                    width: 100%;
                    height: 100%;
                    top: 0;
                    left: 0;
                    transition: all 0.3s ease;
                    border-radius: 6px;
                    text-align: center;
                    color: #fff;
                    background-color: rgba(0, 0, 0, .5);
                    box-sizing: border-box;
                    opacity: 0;
                    cursor: pointer;
                    z-index: 10;
                }
            }
            .img-oper:hover .oper{
                opacity: 1;
            }
            .goods-img-upload i:hover {
                border-color: #00e28b;
            }
        }
    }
}
</style>